package com.codi.api.controller.assets;

import com.codi.api.security.UserUtil;
import com.codi.base.exception.BaseAppException;
import com.codi.base.log.annotation.Loggable;
import com.codi.base.util.EqualsUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.domain.FundCombination;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.domain.UserBank;
import com.codi.bus.core.resultModel.*;
import com.codi.bus.core.service.*;
import com.codi.bus.core.service.model.PortfolioModel;
import com.codi.bus.core.service.model.PortfolioTradeModel;
import com.codi.bus.exception.BaseException;
import com.codi.fcloud.ufx.hssale.query.AccountBankQuery;
import com.codi.message.constant.ErrorConstant;
import com.codi.message.util.MessageUtil;
import com.codi.trade.dto.HsAccoBankQueryDto;
import com.codi.trade.response.HsAccoBankQueryResponse;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by asus on 2018/6/15.
 */
@Controller
@RestController
@RequestMapping("/localAssets")
@Slf4j
public class LocalAssetsController {
    @Autowired
    private LocalAssetsService localAssetsService;

    @Resource
    private FundCombinationService fundCombinationService;

    @Resource
    private UserService userService;

    @Resource
    private AccountBankQuery accountBankQuery;

    @Resource
    private BankService bankService;

    @Resource(name="queryService")
    private QueryService queryService;


    /**
     * 普通基金 列表
     * @param requestNum
     * @param beginNum
     * @return
     */
    @GetMapping("fundShareList")
    @ResponseBody
    @Loggable
    public ShareListResult getFundShareList(Integer requestNum, Integer beginNum) {

        ShareListResult result = new ShareListResult();
        try {
            result = localAssetsService.getAllShares(UserUtil.getLoginUserId(), requestNum, beginNum);
        } catch (BaseAppException e) {
            e.printStackTrace();
            throw new BaseException(ErrorConstant.ERROR_GILDATA_WRONG, result.getErrorMessage(), GlobalConstant.ERROR_TYPE_APPLICATION);
        }

        return result;
    }

    /**
     * 单个普通基金详情
     * @param fundCode
     * @return
     */
    @GetMapping("fundShare")
    @ResponseBody
    @Loggable
    public BaseResult getFundShare(String fundCode) {

        BaseResult result = new BaseResult();
        try {
            result = localAssetsService.getFundShares(UserUtil.getLoginUserId(), fundCode);
        } catch (BaseAppException e) {
            e.printStackTrace();
            throw new BaseException(ErrorConstant.ERROR_GILDATA_WRONG, result.getErrorMessage(), GlobalConstant.ERROR_TYPE_APPLICATION);
        }

        return result;
    }


    /**
     * 查询首页个人总资产
     *
     * @return
     */
    @GetMapping("/assets")
    @Loggable
    public BaseResult getAssets() {
        Long userId = UserUtil.getLoginUserId();
        AssetsResult result = new AssetsResult();
        try {
            result = localAssetsService.queryAssets(userId);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 查询组合具体基金信息
     */
    @GetMapping("/portfolioFunds")
    @Loggable
    public BaseResult portfolioFunds(@RequestParam String portfolioCode) {
        Long userId = UserUtil.getLoginUserId();
        PortfolioModel result = localAssetsService.queryPortfolioFunds(userId, portfolioCode);
        FundCombination fundCombination = fundCombinationService.queryOne(portfolioCode);
        if (fundCombination != null && fundCombination.getAnnualizedIncome() != null) {
            result.setShare("向您推荐一只基金组合，组合年化收益率为" + fundCombination.getAnnualizedIncome().toString() + "%");
        } else {
            result.setShare("向您推荐一只基金组合");
        }

        if (!result.getSuccess() && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }
        // spy 2017-12-13 10:45:00
        if (result.getPortfolioTrades() != null) {
            // 查询用户银行卡列表
            User user = userService.getUser(userId);
            if (Strings.isNullOrEmpty(user.getExternalClientId())) {
                return result;
            }
            HsAccoBankQueryDto queryDto = HsAccoBankQueryDto.builder()
                .client_id(user.getExternalClientId())
                .build();
            List<HsAccoBankQueryResponse> hsBanks = accountBankQuery.query(queryDto);
            if (hsBanks != null) {
                List<PortfolioTradeModel> portfolioTrades = result.getPortfolioTrades();
                portfolioTrades.forEach(item -> {
                    String portfolioTradeAcco = item.getTradeAcco();
                    for (HsAccoBankQueryResponse queryResponse : hsBanks) {
                        if (EqualsUtil.equals(portfolioTradeAcco, queryResponse.getTrade_acco())) {
                            List<UserBank> userBanks = bankService.getBanks(user.getUserId(), queryResponse.getBank_account());
                            if (userBanks == null || userBanks.isEmpty()) {
                                log.warn("userId={},bankNo={}不存在", user.getUserId(), queryResponse.getBank_account());
                            } else {
                                UserBank userBank = new UserBank();
                                if (!GlobalConstant.CAPITAL_MODE_COUNTER.equals(userBanks.get(0).getCapitalMode())) {
                                    userBank = userBanks.get(0);
                                } else {
                                    userBank = userBanks.get(1);
                                }
                                item.setUserBankNo(userBank.getUserBankNo());
                                item.setBankCode(userBank.getBankCode());
                                item.setBankName(userBank.getBankName());
                                item.setBranchBank(userBank.getBranchbank() == null ? "" : userBank.getBranchbank());
                                item.setBranchBankName(userBank.getBankBranchName() == null ? "" : userBank.getBankBranchName());
                                item.setCapitalMode(userBank.getCapitalMode());
                            }
                            break;
                        }
                    }
                });
            } else {
                log.warn("没有该账户对应的银行卡交易账号信息");
            }
        }


        return result;
    }


    /**
     * 查询组合列表
     */
    @GetMapping("/portfolio")
    @Loggable
    public BaseResult portfolioList() {
        AssetsPortfolioResult assetsPortfolioResult = new AssetsPortfolioResult();
        Long userId = UserUtil.getLoginUserId();
        try {
            assetsPortfolioResult = localAssetsService.queryPortfolioList(userId);
        } catch (Exception e) {
            e.printStackTrace();
            assetsPortfolioResult.setSuccess(false);
        }
        return assetsPortfolioResult;
    }

    /**
     * t0提现界面
     *
     * @param fundCode
     * @return
     * @author
     */
    @Loggable
    @GetMapping("/cashChangeInfo")
    @ResponseBody
    public BaseResult queryCashChangeInfo(@RequestParam(name = "fundCode") String fundCode) {

        return localAssetsService.getWalletCashChangeDetails(UserUtil.getLoginUserId(), fundCode);
    }

    /**
     * 获取单个t0基金的详情
     * @param fundCode
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "wallet/detail", method = RequestMethod.GET)
    @ResponseBody
    public WalletDetailResult detail(String fundCode) throws BaseAppException {
        Long userId = UserUtil.getLoginUserId();
        try{
            WalletDetailResult result = localAssetsService.getWalletDetailByFundCode(userId,fundCode);
            result.setRecommendedFundModel(queryService.queryRecommendedFund());//设置推荐基金
            return result;
        }
        catch(Exception e){e.printStackTrace();}

        return null;
    }

    /**
     * 获取单个t0基金资产列表
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "wallet/list", method = RequestMethod.GET)
    @ResponseBody
    public WalletDetailResultV2 walletList() throws BaseAppException {
        Long userId = UserUtil.getLoginUserId();
        try{
            WalletDetailResultV2 result = localAssetsService.getWalletList(userId);
            return result;
        }
        catch(Exception e){e.printStackTrace();}

        return null;
    }
}
